package compiler.ast;

import java.io.PrintStream;

import compiler.tac.BasicBlock;
import compiler.tac.Instruction.Operator;
import compiler.tac.ThreeAddressCode;



public class Designator implements Factor {
	Identifier ident;
	Expression expression;
	
	public Designator (Identifier ident, Expression expr) {
		this.ident = ident;
		this.expression = expr;
	}

	public void printDotFormat(PrintStream out, String node) {
		out.println(node+" [label=\""+ident.name()+"\"];");
		
		if (expression != null) {
			String idxNode = node+0;
			String exprNode = node+1;
			out.println(node+"->"+idxNode+";");
			out.println(idxNode+" [label=\"[ ]\"];");
			out.println(idxNode+"->"+exprNode+";");
			out.println(exprNode+" [label=\"[ ]\"];");
			expression.printDotFormat(out, exprNode);
		}
	}
	
	public String toThreeAddressCode(ThreeAddressCode tac, BasicBlock prev)
	{
		if(expression != null)
		{
			String temp1 = this.expression.toThreeAddressCode(tac, prev);
			String addr = tac.getTempVar();
			prev.addBinaryInstruction(Operator.Add, addr, this.ident.name(), temp1);
			//String data = tac.getTempVar();
			//prev.addUnaryInstruction(Operator.Load, data, addr);
			return addr;
		}
		else {
			return this.ident.name();
		}	
	}
}
